<?php
/*
Copyright (c) 2006, Maurice Svay
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Maurice Svay nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

include_once(dirname(__FILE__).'/../lib/simplepie/simplepie.inc');
include_once(dirname(__FILE__).'/../lib/lib.String.php');
include_once(dirname(__FILE__).'/../lib/spyc-0.2.3/spyc.php');

/**
 * Planet configuration class
 */
class PlanetConfig{
	var $conf;
    
    function PlanetConfig($array){
		$defaultConfig = Array(
			'url' => 'http://www.example.com/',
			'name' => '',
			'items' => 10,
			'shuffle' => 0,
			'refresh' => 240,
			'cache' => 10,
			'nohtml' => 0,
			'postmaxlength' => 0
		);
		
		//User config
		$this->conf = $array;
		
		//Complete config with default config
		foreach ($defaultConfig as $key => $value){
			if (!isset($this->conf[$key])){
				$this->conf[$key] = $value;
			}
		}
    }
    
    function getUrl(){
        return $this->conf['url'];
    }
	
	function getName(){
		return $this->conf['name'];
	}

    function setName($name){
        $this->conf['name'] = $name;
    }
    
    function getCacheTimeout(){
        return $this->conf['refresh'];
    }
	
	function getOutputTimeout(){
		return $this->conf['cache'];
	}
	
	function getShuffle(){
		return $this->conf['shuffle'];
	}
    
    function getMaxDisplay(){
        return $this->conf['items'];
    }
	
	function getNoHTML(){
		return $this->conf['nohtml'];
	}
	
	function getPostMaxLength(){
		return $this->conf['postmaxlength'];
	}
    
    function toYaml(){
        return Spyc::YAMLDump($this->conf,4);
    }
}

/**
 * Planet person
 */
class PlanetPerson{
    var $name;
    var $feed;
    var $website;
    
    function PlanetPerson($name, $feed, $website){
        $this->name = $name;
        $this->feed = $feed;
        $this->website = $website;
    }
    
    function getFeed(){
        return $this->feed;
    }
    
    function getName(){
        return $this->name;
    }
    
    function getWebsite(){
        return $this->website;
    }
    
    function compare($person1, $person2){
        return strcasecmp($person1->name, $person2->name);
    }
}

/**
 * Planet item
 */
class PlanetItem{
    var $url;
    var $title;
    var $date;
    var $author;
    var $content;
    var $owner;
    
    function PlanetItem($url, $title, $date, $author, $content, &$owner){
        $this->url = $url;
        $this->title = $title;
        $this->date = $date;
        $this->author = $author;
        $this->content = $content;
        $this->owner = $owner;
    }
    
    /**
     * Returns item permalink
     * @return string Item permalink (URL)
     */
    function getUrl(){
        return $this->url;
    }
    
    /**
     * Returns item title
     * @return string Item title
     */
    function getTitle(){
        return $this->title;
    }
    
    /**
     * Returns item date as timestamp
     * @return int Item date timestamp
     */
    function getDate(){
        return $this->date;
    }
    
    /**
     * Returns item author name
     * @return string Item author name
     */
    function getAuthor(){
        return $this->author;
    }
    
    /**
     * Returns item content
     * @return string Item content
     */
    function getContent(){
        return $this->content;
    }
    
    /**
     * Return item owner
     * @return PlanetPerson Item owner
     */
    function getOwner(){
        return $this->owner;
    }
    
    function compare($item1, $item2){
        if ($item1->date == $item2->date){
            return 0;
        }
        else if ($item1->date < $item2->date){
            return 1;
        }
        return -1;
    }
}

/**
 * Planet, main app class
 */
class Planet{
    var $config;
    var $items;
    var $people;
    var $simplepie;
    
    function Planet($config=null){
        if ($config == null){
            $this->config = new PlanetConfig();
        }
        else{
            $this->config = $config;
        }
    }
    
    /**
     * Adds a person to the planet
     * @param PlanetPerson person
     */
    function addPerson(&$person){
        $this->people[] = $person;
    }
    
    /**
     * Load feeds
     */
    /**/
    function loadFeeds(){
        foreach ($this->people as $person){
            $this->simplepie = new SimplePie();
            $this->simplepie->feed_url($person->getFeed());
            $this->simplepie->cache_max_minutes($this->config->getCacheTimeout()+rand(0,30)); //add some random to avoid mass download
            $this->simplepie->init();
            if (($this->simplepie->data) && ($this->simplepie->get_item_quantity() > 0)){
				$items = $this->simplepie->get_items();
				foreach ($items as $item) {
					$content = '';
					$item_authors = $item->get_authors();
					$authors = Array();
					if (is_array($item_authors)){
						foreach ($item_authors as $author){
                            if (trim($author->get_name()) != ''){
                                $authors[] = $author->get_name();
                            }else{
                                $authors[] = $person->getName();
                            }
						}
					}
					else{
						$authors[] = $person->getName();
					}
					
					//Strip HTML
					if ($this->config->getNoHTML() == 1){
						$content = strip_tags($item->get_description());
					}else{
						$content = $item->get_description();
					}
					
					//Truncate content
					if ($this->config->getPostMaxLength() > 0){
						$content = smarty_modifier_html_substr(
									$content,
									$this->config->getPostMaxLength(),
									'&hellip;'
						);
					}
					
                    $this->items[] = new PlanetItem(
                        $item->get_permalink(),
                        $item->get_title(),
                        $item->get_date('U'),
                        implode(',',$authors),
                        $content,
                        $person
                    );
                }
            }
            unset($this->simplepie);
        }
        usort($this->items, array('PlanetItem','compare'));
    }
    
    /**
     * Returns feed items
     */
    function getItems(){
        return $this->items;
    }
    
    function getPeople(){
        return $this->people;
    }
}

?>